﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lib.Web.Mvc.JQuery.JqGrid;
using ICDA.Repositories.ICDA;
using System.Text;
using System.IO;
using ICDA.Web.Models;
using ICDA.Models;
using ICDA.Models.Entity;
using ICDA.Web.Helper;
using System.Collections;

namespace ICDA.Web.Controllers
{
    public class HomeController : Controller
    {
        #region Fields
        IRepository _repository;
        LogOnModel loginModel = new LogOnModel();
        IEnumerable<ActivityTable> activity;
        private static UserModel _userModel;
        #endregion

        #region Constructors
        
        public static UserModel userModel
        {
            get
            {
                if (_userModel == null)
                {
                    _userModel = new UserModel();
                }
                return _userModel;
            }
        }
        public HomeController(): this(new Repository())
        {
        }

        public HomeController(IRepository repository)
        {
            _repository = repository;
        }

        #endregion

        #region Actions

        public ActionResult Index()
        {
            if (Session["UID"] != null)
            {
                ViewBag.Message = "Welcome to ICDA";
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        public ActionResult About()
        {
            return View();
        }
        public ActionResult Activity()
        {
            if (Session["UID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        public ActionResult ActivityHistory()
        {
            if (Session["UID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetTask(JqGridRequest request, CustomSearchViewModel viewModel)
        {
            DatetTimeHelper dtHelper = new DatetTimeHelper();
            DateTime sdate = dtHelper.weekStartDate;
            DateTime edate = dtHelper.weekEndDate;
            string userID = Session["UID"].ToString().Trim();
            string UID = loginModel.UserName;
            if (userModel.Role == "Admin")
            {
                activity = _repository.activity.Where(u =>u.ActivityDate >= sdate && u.ActivityDate <= edate);
            }
            else
            {
                activity = _repository.activity.Where(u => u.UserID == userID && u.ActivityDate >= sdate && u.ActivityDate <= edate);
            }
            int totalRecords = _repository.activity.Where(u => u.UserID == userID).Count();
            var data = _repository.activity.Where(u => u.UserID == userID);
            JqGridResponse response = new JqGridResponse()
            {
                //Total pages count
                TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
                //Page number
                PageIndex = request.PageIndex,
                //Total records count
                TotalRecordsCount = totalRecords
            };
            //Table with rows data
            foreach (ActivityTable task in activity)
            {
                response.Records.Add(new JqGridRecord(Convert.ToString(task.ID), new List<object>()
                {
                    task.ID,
                    task.Task,
                    task.ActivityDate,
                    task.TimeSpend,
                    task.OverTime,
                    task.UserID
                }));
            }

            //Return data as json
            return new JqGridJsonResult() { Data = response };
        }
        public ActionResult InsertTask(ActivityViewModel viewModel)
        {
            string uid= Session["UID"].ToString().Trim();
            string userID = loginModel.UserName;
            ActivityTable act= new ActivityTable{
            ActivityDate = viewModel.ActivityDate,
            OverTime = viewModel.OverTime,
            Task = viewModel.Task,
            UserID = uid,
            TimeSpend = viewModel.TimeSpend
            };
            _repository.AddTask(act);
            return Json(_repository.SaveChanges());
            
        }
        public ActionResult UpdateTask(ActivityViewModel viewModel)
        {
            string uid = Session["UID"].ToString().Trim();
            string userID = loginModel.UserName;
            ActivityTable act = _repository.activity.Where(u => u.ID == viewModel.ID).FirstOrDefault();
            act.ActivityDate = viewModel.ActivityDate;
            act.OverTime = viewModel.OverTime;
            act.Task = viewModel.Task;
            act.UserID = uid;
            act.TimeSpend = viewModel.TimeSpend;
            return Json(_repository.SaveChanges());

        }
        public ActionResult DeleteTask(ActivityViewModel viewModel)
        {
            string uid = Session["UID"].ToString().Trim();
            int id = viewModel.ID;
            string userID = loginModel.UserName;
            ActivityTable act = _repository.activity.Where(u => u.ID == id).FirstOrDefault();
            _repository.DeleteTask(act);
            return Json(_repository.SaveChanges());

        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetHistoricalRecords(JqGridRequest request, CustomSearchViewModel viewModel)
        {
            string userID = Session["UID"].ToString().Trim();
            string UID = loginModel.UserName;
            int totalRecords = 0;
            activity = _repository.activity.Where(u => u.UserID == userID);
            totalRecords = _repository.activity.Where(u => u.UserID == userID).Count();
            totalRecords = _repository.activity.Count();
            var data = _repository.activity.Where(u => u.UserID == userID);
            JqGridResponse response = new JqGridResponse()
            {
                //Total pages count
                TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
                //Page number
                PageIndex = request.PageIndex,
                //Total records count
                TotalRecordsCount = totalRecords
            };
            //Table with rows data
            var acttable = _repository.activity.Join(_repository.users, u1 => u1.UserID, u2 => u2.UserID, (u1, u2) => new { Name = u2.Name, ID = u1.ID, UID = u1.UserID, Task = u1.Task, ActivityDate = u1.ActivityDate, TimeSpend =u1.TimeSpend,OverTime= u1.OverTime});
            foreach (var task in acttable)
            {
                response.Records.Add(new JqGridRecord(Convert.ToString(task.ID), new List<object>()
                {
                    task.ID,
                    task.Name.Trim(),
                    task.Task,
                    task.ActivityDate,
                    task.TimeSpend,
                    task.OverTime,
                    task.UID
                }));
            }

            //Return data as json
            return new JqGridJsonResult() { Data = response };
        }
        /// <summary>
        /// Import configuration for jqGrid in json
        /// </summary>
        /// <param name="id">The jqGrid identifier</param>
        /// <returns>The jqGrid configuration in json format</returns>
        [Lib.Web.Mvc.NoCache]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult ImportConfiguration(string id)
        {
            JqGridConfiguration configuration = null;
            //Do we already have configuration in Session
            if (Session[id] != null)
                //If yes, the use it
                configuration = (JqGridConfiguration)Session[id];
            else
            {
                //If no, then create one
                configuration = new JqGridConfiguration()
                {
                    Settings = new JqGridOptions(id)
                    {
                        ColumnsRemaping = new List<int>() { 0, 1, 2, 3, 4, 5, 6 },
                        RowsNumber = 10,
                        SortingName = "ID",
                        SortingOrder = JqGridSortingOrders.Asc,
                        ViewRecords = true
                    }
                };
                configuration.Settings.ColumnsNames.AddRange(new string[] { "ID", "UserID", "Task", "TimeSpend", "ActivityDate", "OverTime" });
                configuration.Settings.ColumnsModels.AddRange(new JqGridColumnModel[]
                {
                     new JqGridColumnModel("ID") { Index = "ID" },
                    new JqGridColumnModel("UserID") { Index = "UserID" },
                    new JqGridColumnModel("Task") {  Index = "Task" },
                    new JqGridColumnModel("TimeSpend") {  Index = "TimeSpend" },
                    new JqGridColumnModel("ActivityDate") {  Index = "ActivityDate" },
                    new JqGridColumnModel("OverTime") {  Index = "OverTime" }
                });
            }

            //Those settings should be set always "just in case"
            configuration.Settings.Url = Url.Action("Activity", "Home");
            configuration.Settings.DataType = JqGridDataTypes.Json;
            configuration.Settings.MethodType = JqGridMethodTypes.Post;
            configuration.Settings.Pager = true;
            return new JqGridJsonResult() { Data = configuration };
        }

        /// <summary>
        /// Exports configuration for jqGrid
        /// </summary>
        /// <param name="configuration">The jqGrid configuration</param>
        /// <returns>An empty result</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public EmptyResult ExportConfiguration(JqGridConfiguration configuration)
        {
            //Store configuration in Session 
            Session[configuration.Settings.Id] = configuration;
            //Return empty result, it will be ignored
            return new EmptyResult();
        }
        #endregion

        #region Methods
        private string GetFilter(string searchingName, JqGridSearchOperators searchingOperator, string searchingValue)
        {
            string searchingOperatorString = String.Empty;
            switch (searchingOperator)
            {
                case JqGridSearchOperators.Eq:
                    searchingOperatorString = "=";
                    break;
                case JqGridSearchOperators.Ne:
                    searchingOperatorString = "!=";
                    break;
                case JqGridSearchOperators.Lt:
                    searchingOperatorString = "<";
                    break;
                case JqGridSearchOperators.Le:
                    searchingOperatorString = "<=";
                    break;
                case JqGridSearchOperators.Gt:
                    searchingOperatorString = ">";
                    break;
                case JqGridSearchOperators.Ge:
                    searchingOperatorString = ">=";
                    break;
            }

            if ((searchingName == "ProductID") || (searchingName == "SupplierID") || (searchingName == "CategoryID"))
                return String.Format("{0} {1} {2}", searchingName, searchingOperatorString, searchingValue);

            if ((searchingName == "ProductName"))
            {
                switch (searchingOperator)
                {
                    case JqGridSearchOperators.Bw:
                        return String.Format("{0}.StartsWith(\"{1}\")", searchingName, searchingValue);
                    case JqGridSearchOperators.Bn:
                        return String.Format("!{0}.StartsWith(\"{1}\")", searchingName, searchingValue);
                    case JqGridSearchOperators.Ew:
                        return String.Format("{0}.EndsWith(\"{1}\")", searchingName, searchingValue);
                    case JqGridSearchOperators.En:
                        return String.Format("!{0}.EndsWith(\"{1}\")", searchingName, searchingValue);
                    case JqGridSearchOperators.Cn:
                        return String.Format("{0}.Contains(\"{1}\")", searchingName, searchingValue);
                    case JqGridSearchOperators.Nc:
                        return String.Format("!{0}.Contains(\"{1}\")", searchingName, searchingValue);
                    default:
                        return String.Format("{0} {1} \"{2}\"", searchingName, searchingOperatorString, searchingValue);
                }
            }

            return String.Empty;
        }
        #endregion
    }
}
